import React from 'react';
import { Upload, Button, Icon } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';

/**
 *
 * @param {String} value 一个文件的相对地址
 */
const getFileList = (value) => {
  let _value = value;
  if (typeof value === 'string') {
    _value = [{
      uid: value,
      name: value,
      status: 'done',
      response: {
        path: value,
        status: '1',
      },
    }];
  }
  return _value || [];
};

// 专门用于上传mp3的组件，限制上传的文件数量是1个，超出不允许上传
class RecordUpload extends React.Component {
  constructor(p) {
    super(p);
    const { value } = this.props;
    this.state = {
      fileList: getFileList(value),
    };
  }
  render() {
    const { value, onChange } = this.props;
    return (
      <div style={{ width: '100%', display: 'inline-block' }}>
        <Upload
          name="file"
          action="/audiorecord/uploadfile"
          accept="audio/*"
          data={{
            type: 'mp3',
            folder: 'audio',
          }}
          fileList={getFileList(value)}
          onChange={({ fileList }) => {
            if (fileList.length) {
              if (fileList[0].response) {
                onChange(_.get(fileList, '[0].response.path'));
              } else {
                onChange(fileList);
              }
            } else {
              onChange(fileList);
            }
            this.setState({
              fileList,
            });
          }}
        >
          {
            _.get(this, 'state.fileList.length') === 0 && (
              <Button>
                <Icon type="upload" /> 上传mp3
              </Button>
            )
          }
        </Upload>
      </div>
    );
  }
}

RecordUpload.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
};

export default RecordUpload;
